package com.example.study

import android.graphics.Canvas
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.study.databinding.ListItemBinding
import com.example.study.page.Pages

/**
 * Created by lijinxi on 2024/2/27
 * @Description:
 */
class CustomRecyclerAdapter(private val viewModel: ListViewModel) :
    RecyclerView.Adapter<CustomRecyclerAdapter.CustomViewHolder>() {
    inner class CustomViewHolder(private val binding: ListItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(text: String) {
            binding.text.text = text
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
        val binding = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CustomViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return Pages.entries.size
    }

    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        holder.bind(Pages.entries[position].pageName())
        holder.itemView.setOnClickListener {
            viewModel.currentIndex.postValue(position)
        }
    }

    class CustomItemDecoration(
        private val borderWidth: Float,
        private val borderColor: Int,
    ) : RecyclerView.ItemDecoration() {

        override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            for (i in 0 until parent.childCount) {
                val child = parent.getChildAt(i)

                val painter = Paint().apply {
                    color = borderColor
                    style = Paint.Style.STROKE
                    strokeWidth = borderWidth / 2
                }
                c.drawLine(
                    parent.left + borderWidth / 2,
                    child.bottom - borderWidth / 2,
                    parent.width - parent.paddingRight - borderWidth / 2,
                    child.bottom - borderWidth / 2,
                    painter
                )
            }
            super.onDraw(c, parent, state)
        }
    }
}